package com.derbtec.refale.transaction;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.derbtec.refale.R;
import com.derbtec.refale.activities.LoginActivity;

public class DoLoginAsyncTask extends AsyncTask<String, Integer, Integer> {
	
	private Activity activity;
	private String cookiestring;
	private ProgressDialog pdia;
	
	public DoLoginAsyncTask(Activity activity) {
		this.activity = activity;
	}

	protected void onPreExecute(){ 
	   super.onPreExecute();
	        pdia = new ProgressDialog((LoginActivity) activity);
	        pdia.setMessage("Connecting...");
	        pdia.setTitle(R.string.login);
	        pdia.show();
	        //pdia.getWindow().setGravity(Gravity.CENTER);
	}
	
	protected Integer doInBackground(String... params) {
		int responsetype = -1;
		//Generate JSON-Object
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("user", params[0]);
			jsonObject.put("pass", params[1]);
			JSONArray jsonarray = new JSONArray();
			jsonarray.put(jsonObject);
			HttpParams httpparams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpparams, HttpVersion.HTTP_1_1);
			HttpClient client = new DefaultHttpClient(httpparams);
			HttpPost post = new HttpPost("http://derb.square7.ch/jsonlogin.php");
			StringEntity entity = new StringEntity(jsonarray.toString());
			post.setEntity(entity);
			post.setHeader("Accept", "applcation/json");
			post.setHeader("Content-type", "applcation/json");
			HttpResponse response = client.execute(post);
			Log.d("HTTPSTATUS", ""+response.getStatusLine().getStatusCode());
			InputStream is = response.getEntity().getContent();
			BufferedReader bfr = new BufferedReader(new InputStreamReader(is));
			String line = bfr.readLine();
			String newline;
			while ((newline = bfr.readLine()) != null) {
				line += newline;
			}
			responsetype = Integer.parseInt(line.substring(1));
			if (response.getStatusLine().getStatusCode() == 200 && responsetype >= 0){
				cookiestring = response.getHeaders("Set-Cookie")[0].getValue();
				Log.d("COOOOKIEEEEE",cookiestring);
			}
			Log.d("JSONresponse", line);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return responsetype;
	}
	
	protected void onProgressUpdate(Integer... progress) {
	    
	}
	
	protected void onPostExecute(Integer result) {
		pdia.dismiss();
		if (result >= 0)
		{
			((LoginActivity) activity).processLogin(cookiestring, result);
		}
		else
		{
			((LoginActivity) activity).denyLogin(result);
		}
	}
}
